package com.gt.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Set;

@Service
public class RedisZSetService {
    @Autowired
    private RedisTemplate redisTemplate;

    public void add(){
        redisTemplate.opsForZSet().add("leaderboard", "user1", 100);
        redisTemplate.opsForZSet().add("leaderboard", "user2", 90);
        redisTemplate.opsForZSet().add("leaderboard", "user3", 80);
    }
    public void incrementScore() {
        redisTemplate.opsForZSet().incrementScore("leaderboard", "user1", 10); // 给user1增加10分
    }
    public void remove() {
        redisTemplate.opsForZSet().remove("leaderboard", "user3"); // 移除user3
    }
    /**
     * 获取zst集合分数
     * @param key 主键
     * @param member 成员
     * @return
     */
    public Double getZsetScore() {
        return redisTemplate.opsForZSet().score("leaderboard", "user3");
    }
    /**
     * 获取集合总数
     */
    public Long getZsetSize() {
        return redisTemplate.opsForZSet().zCard("leaderboard");
    }

    public void rank(){
        Long rank = redisTemplate.opsForZSet().rank("leaderboard", "user1"); // 获取user1的排名
    }
    /**
     * 获取 ZSet 中成员的排名（从大到小排序）
     * @param key ZSet 的键
     * @param member 成员
     * @return 排名（从 0 开始）
     */
    public Long reverseRank() {
        return redisTemplate.opsForZSet().reverseRank("leaderboard", "user1");
    }
    public void range(){
        Set<String> users = redisTemplate.opsForZSet().range("leaderboard", 0, -1); // 获取分数前10的用户
    }
    public Set<String> getTopUsers() {
        return redisTemplate.opsForZSet().range("leaderboard", 0, -1); // 获取前10名用户
    }
    public Set<String> getReverseTopUsers() {
        return redisTemplate.opsForZSet().reverseRange("leaderboard", 0, -1); // 获取前10名用户
    }

    public Set<DefaultTypedTuple<Object>> getTopUsersWithScores() {
        return redisTemplate.opsForZSet().rangeWithScores("leaderboard", 0, -1); // 获取前10名用户
    }
    public Set<DefaultTypedTuple<Object>> getReverseTopUsersWithScores() {
        return redisTemplate.opsForZSet().reverseRangeWithScores("leaderboard", 0, -1); // 获取前10名用户
    }
}
